package com.mengxin.secondkill.aop;

import com.google.common.collect.ImmutableList;
import com.mengxin.secondkill.annotation.Limit;
import com.mengxin.secondkill.constants.LimitType;
import com.mengxin.secondkill.constants.RespCode;
import com.mengxin.secondkill.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.lang.reflect.Method;

/**
 * @author mengxin
 * @date 2020/12/12 15:09
 */
@Aspect
@Slf4j
@Component
public class LimitInterceptor {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private static final String UNKNOWN = "unknown";

    @Before("@annotation(com.mengxin.secondkill.annotation.Limit)")
    public void interceptor(JoinPoint pjp) {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        Limit limitAnnotation = method.getAnnotation(Limit.class);
        LimitType limitType = limitAnnotation.limitType();
        String name = limitAnnotation.name();
        String key;
        int limitPeriod = limitAnnotation.period();
        int limitCount = limitAnnotation.count();
        switch (limitType) {
            case IP:
                key = getIpAddress();
                break;
            case CUSTOMER:
                key = limitAnnotation.key();
                break;
            default:
                key = StringUtils.upperCase(method.getName());
        }
        ImmutableList<String> keys = ImmutableList.of(StringUtils.join(limitAnnotation.prefix(), key));
        String luaScript = buildLuaScript();
        RedisScript<Long> redisScript = new DefaultRedisScript<>(luaScript, Long.class);
        Long count = redisTemplate.execute(redisScript, keys, limitCount, limitPeriod);
        log.info("Access try count is {} for name={} and key = {}", count, name, key);
        if (count == null || count.intValue() > limitCount) {
            log.error("You have been dragged into the blacklist");
            throw new ServiceException(RespCode.COMMON_FAIL_CODE, "系统繁忙");
        }
    }

    /**
     * 限流 脚本
     *
     * @return lua脚本
     */
    public String buildLuaScript() {
        InputStreamReader intput = null;
        StringBuilder builder = new StringBuilder();
        try {
            Resource resource = new ClassPathResource("lua/redis_rate_limit.lua");
            // 修改部分
            intput = new InputStreamReader(resource.getInputStream());
            BufferedReader reader = new BufferedReader(intput);
            String conent = null;
            while ((conent = reader.readLine()) != null) {
                builder.append("\n").append(conent);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return builder.toString();
    }

    /**
     * 获取IP地址
     *
     * @return
     */
    public String getIpAddress() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
